package com.qhong.modules.controller;

import com.qhong.annotation.AuthIgnore;
import com.qhong.modules.entity.User;
import com.qhong.modules.response.R;
import com.qhong.modules.service.UserService;
import com.qhong.util.JwtUtils;
import com.qhong.util.ServletUtils;
import com.qhong.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by qhong on 2018/6/5 16:08
 **/
@RestController
@RequestMapping("/login")
public class LoginController {


	@Autowired
	private UserService userService;
	@Autowired
	private JwtUtils jwtUtils;

	@RequestMapping(value="/login",method= RequestMethod.POST)
	public R login(HttpServletRequest request, Map<String, Object> map) throws Exception{
		HttpSession session=ServletUtils.getSession();
		String username=map.get("name").toString();
		String password=map.get("pwd").toString();
		UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(usernamePasswordToken);   //完成登录
			User user=(User) subject.getPrincipal();
			session.setAttribute("user", user);
		} catch(Exception exception) {

		}
		// 登录失败从request中获取shiro处理的异常信息。
		// shiroLoginFailure:就是shiro异常类的全类名.
		String exception = (String) request.getAttribute("shiroLoginFailure");
		System.out.println("exception=" + exception);
		String msg = "";
		if (exception != null) {
			if (UnknownAccountException.class.getName().equals(exception)) {
				System.out.println("UnknownAccountException -- > 账号不存在：");
				msg = "UnknownAccountException -- > 账号不存在：";
			} else if (IncorrectCredentialsException.class.getName().equals(exception)) {
				System.out.println("IncorrectCredentialsException -- > 密码不正确：");
				msg = "IncorrectCredentialsException -- > 密码不正确：";
			} else if ("kaptchaValidateFailed".equals(exception)) {
				System.out.println("kaptchaValidateFailed -- > 验证码错误");
				msg = "kaptchaValidateFailed -- > 验证码错误";
			} else {
				msg = "else >> "+exception;
				System.out.println("else -- >" + exception);
			}
		}
		// 此方法不处理登录成功,由shiro进行处理
		if(StringUtils.isNotEmpty(msg)){
			return R.error(msg);
		}
		return R.ok("success");
	}

	@RequestMapping("/logOut")
	public String logOut() {
		HttpSession session=ServletUtils.getSession();
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
//      session.removeAttribute("user");
		return "login";
	}

	@RequestMapping("/403")
	public String unauthorizedRole(){
		System.out.println("------没有权限-------");
		return "403";
	}

	/**
	 * 登录
	 */
	@PostMapping("/jwt/login")
	@AuthIgnore
	public R login2(@RequestBody User u){

		//用户登录
		long userId =userService.addUser(u);

		//生成token
		String token = jwtUtils.generateToken(userId);

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("expire", jwtUtils.getExpire());

		return R.ok(map);
	}
}
